/*
* @Author: xfy
* @Date:   2017-08-29 14:14:02
* @Last Modified by:   xfy
* @Last Modified time: 2017-08-29 18:27:13
*/
'use strict';
require('./index.css');
require('page/common/nav/index.js');
require('page/common/header/index.js');
var navSide         = require('page/common/nav-side/index.js');
var _supper         = require('util/supper.js');
var _user           = require('service/user-service.js');
var templateIndex   = require('./index.string');

//page逻辑部分
var page = {
    init : function(){
        this.onLoad();
        this.bindEvent();
    },
    onLoad : function(){
        //初始化左侧菜单
        navSide.init({
            name : 'user-center'
        });
        //加载用户信息
        this.loadUserInfo();
    },
    bindEvent : function(){
        var _this = this;
        //点击提交按钮后的动作
        $(document).on('click', '.btn-submit', function(){
            var userInfo = {
                idNo            : $('#idNo').text(),
                sex             : $.trim($('#update-sex').val()),
                department      : $.trim($('#update-department').val()),
            },
            validateResult = _this.validateForm(userInfo);
            //验证成功
            if(validateResult.status){
                //更新用户信息
                _user.updateUserInfo(userInfo, function(res, msg){
                    _supper.successTips(msg);
                    window.location.href = './user-center.html?idNo' + $('#idNo').text();
                }, function(errMsg){
                    _supper.errorTips(errMsg);
                });
            }
            //验证失败
            else{
                _supper.errorTips(validateResult.msg);
            }
        });
    },
    //加载用户信息
    loadUserInfo : function(){
        var userHtml = '';
        _user.getUserInfo(function(res){
            res.sex = res.sex ? '男' : '女'
            userHtml = _supper.renderHtml(templateIndex, res);
            $('.panel-body').html(userHtml);
        }, function(errMsg){
            $('.panel .panel-body .loading').hide();
            $('.panel .panel-body .error-tip').show();
        });
    },
    //验证字段信息
    validateForm : function(formData){
        var result = {
            status  : false,
            msg     : ''
        };
        //验证部门
        if(formData.department == ""){
            result.msg = '部门不能为空';
            return result;
        }
        //验证性别
        if(formData.sex != "男" && formData.sex != "女"){
            result.msg = '请输入正确的性别，男或女';
            return result;
        }

        formData.sex == "男" ? formData.sex = 1 : formData.sex = 0;
        
        result.status   = true;
        result.msg      = '验证通过';
        return result;
    }
};
$(function(){
    page.init();
});